package com.nike.amoeba.ui.frg

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.TimeUtils
import com.kingja.loadsir.core.LoadService
import com.nike.amoeba.R
import com.nike.amoeba.adapter.StockManageListAdapter
import com.nike.amoeba.api.UIHelper
import com.nike.amoeba.base.BaseFragment
import com.nike.amoeba.bean.DataBean
import com.nike.amoeba.bean.RfidStateBean
import com.nike.amoeba.bean.db.StockManageEpcBean
import com.nike.amoeba.databinding.FStockManageListBinding
import com.nike.amoeba.ext.SCAN_STATUS_SCAN
import com.nike.amoeba.ext.WAREHOUSE_RU_TYPE
import com.nike.amoeba.ext.init
import com.nike.amoeba.ext.loadListData
import com.nike.amoeba.ext.loadServiceInit
import com.nike.amoeba.ext.setNbOnItemClickListener
import com.nike.amoeba.ext.showLoading
import com.nike.amoeba.mar.eventViewModel
import com.nike.amoeba.viewmodel.RfidModel
import com.nike.amoeba.viewmodel.StockManageModel
import com.nike.amoeba.weight.recyclerview.SpaceItemDecoration
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.nav
import java.util.concurrent.locks.ReentrantLock


/**
 * User: Nike
 *  2024/5/13 09:49
 *      出入库列表
 */
class StockManageListFrg: BaseFragment<StockManageModel, FStockManageListBinding>(){

    val adapter: StockManageListAdapter by lazy { StockManageListAdapter(arrayListOf()) }

    lateinit var loadsir: LoadService<Any>

    var stockType: Int = 0

    val stockManageModel: StockManageModel by activityViewModels()

    val rfidModel: RfidModel by activityViewModels()

    val lock = ReentrantLock()

    override fun initView(savedInstanceState: Bundle?) {
        arguments?.let {
            mViewModel.code.set(it.getString("code"))
            mViewModel.batchNo.set(it.getString("batchNo"))
            stockType = it.getInt("stockType")
        }
        mDatabind.viewmodel = mViewModel
        mDatabind.click = ProxyClick()
        mViewModel.state.set(getString(R.string.start))
        mViewModel.save.set(getString(R.string.submit_all))
        //状态页配置
        loadsir = loadServiceInit(mDatabind.swipeRefresh) {
            lazyLoadData()
        }

        //初始化recyclerView
        mDatabind.recyclerView.init(LinearLayoutManager(context), adapter).let {
            it.addItemDecoration(SpaceItemDecoration(ConvertUtils.dp2px(20f), ConvertUtils.dp2px(20f), true))
        }

        adapter.run {
            setNbOnItemClickListener{adapter, view, position ->
                val bean = adapter.data[position] as DataBean
                UIHelper.starStockEpcFrg(nav(), mViewModel.batchNo.get(), bean, stockType, mViewModel.code.get())
            }

            setOnItemClickListener(object : StockManageListAdapter.OnItemClickListener{
                override fun onScannedClick() {

                }

                override fun onDetailedClick(content: String?, AssetNo: String?) {
                    UIHelper.startStockTextFrg(nav(), content, AssetNo)
                }
            })
        }

//        mDatabind.swipeRefresh.isRefreshing = true
        mDatabind.swipeRefresh.setOnRefreshListener {
            mViewModel.onStockManageList(mViewModel.batchNo.get(), stockType, mViewModel.code.get())
        }

        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onResume(owner: LifecycleOwner) {
                super.onResume(owner)
                setToolBarTitle(mViewModel.batchNo.get()!!)
            }

            override fun onPause(owner: LifecycleOwner) {
                super.onPause(owner)
                rfidModel.rfidDataCallback.value = null
                rfidModel.isOpen.value = false
                mViewModel.state.set(getString(R.string.start))
            }
        })
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.listBean.observe(viewLifecycleOwner, Observer {
            loadListData(it, adapter, loadsir, mDatabind.recyclerView, mDatabind.swipeRefresh, it.pageSize)
        })
        stockManageModel.updateStockManageListCallback.observe(viewLifecycleOwner, {
            lazyLoadData()
        })
        rfidModel.rfidDataCallback.observe(viewLifecycleOwner, {
            if (it == null)return@observe
            lock.lock()
            try {
                val tagId = it.tagId
                mViewModel.viewModelScope.launch(Dispatchers.IO) {
                    adapter.data.forEachIndexed { index, dataBean ->
                        var stockId = dataBean.RoNo + mViewModel.batchNo.get() + dataBean.AssetNo
                        val orderEpc = dataBean.OrderEpc
                        if (orderEpc != null){
                            val datalist = orderEpc.datalist
                            if (stockType == WAREHOUSE_RU_TYPE){
                                onRuStock(datalist, tagId, stockId, dataBean, index, orderEpc)
                            }else{
                                onChuStock(datalist, tagId, stockId, dataBean, index, orderEpc)
                            }
                        }
                    }
                }
            } finally {
                lock.unlock()
            }
        })
        rfidModel.scanDataCallback.observe(viewLifecycleOwner, {
            if (it != null && viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
                rfidModel.rfidDataCallback.value = RfidStateBean(
                    tagId = it,
                    scanStatus = SCAN_STATUS_SCAN,
                    rssi = "0")
            }
        })
    }

    private suspend fun onRuStock(
        datalist: ArrayList<DataBean>?,
        tagId: String?,
        stockId: String,
        dataBean: DataBean,
        index: Int,
        orderEpc: DataBean
    ) {
        var bean = datalist?.find { it.EPC.equals(tagId) }
        if (bean != null && dataBean.Type != 1) {
            //避免重复
            var b1 = mViewModel.stockManageEpcDao.find(bean.EPCRoNo!!)
            if (b1?.type == 1)return
            //匹配的存起来
            var epcBean = StockManageEpcBean()
            epcBean.id = bean.id
            epcBean.ids = dataBean.id
            epcBean.EPCRoNo = bean.EPCRoNo
            epcBean.epc = bean.EPC
            epcBean.SUnitName = bean.SUnitName
            epcBean.MURoNo = bean.MURoNo
            epcBean.SRoNo = bean.SRoNo
            epcBean.BatchNo = mViewModel.batchNo.get()
            epcBean.type = 1
            epcBean.isCheckedSave = true
            epcBean.createTime = TimeUtils.getNowString()
            mViewModel.stockManageEpcDao.insertOrUpdate(epcBean)
            eventViewModel.playMusic.postValue(true)
            //设置规格数量
            dataBean.Info?.forEach {
                if (bean.MURoNo == it.MURoNo) {
                    val skuAll = mViewModel.stockManageEpcDao.findSkuAll(epcBean.ids!!, it.MURoNo!!, mViewModel.batchNo.get())
                    it.allNum = skuAll.size
                }
            }
            val skuAll = mViewModel.stockManageEpcDao.findSkuAll(epcBean.ids!!, mViewModel.batchNo.get())
            val count = dataBean?.Info?.sumOf { it.NeedNum } ?: 0
            if (skuAll.size == count){
                dataBean.Type = 1
            }
            dataBean.BatchNo = mViewModel.batchNo.get()
            Handler(Looper.getMainLooper()).post {
                adapter.setData(index, dataBean)
            }
            return
        }
    }

    private suspend fun onChuStock(
        datalist: ArrayList<DataBean>?,
        tagId: String?,
        stockIds: String,
        dataBean: DataBean,
        index: Int,
        orderEpc: DataBean
    ) {
        datalist?.forEach { bean ->
            val findMURoNoAll = mViewModel.stockManageEpcDao.findMURoNoAll(bean?.id!!, bean.MURoNo!!)
            if (findMURoNoAll.size != bean.NeedNum && dataBean.Type != 1){
                var epcBean = bean.EPCList?.find { it.EPC == tagId }
                if (epcBean != null && epcBean.Type != 1){
                    var stockEpcBean = StockManageEpcBean()
                    stockEpcBean.id = bean.id
                    stockEpcBean.ids = dataBean.id
                    stockEpcBean.EPCRoNo = epcBean?.EPCRoNo
                    stockEpcBean.epc = epcBean?.EPC
                    stockEpcBean.SUnitName = bean.SUnitName
                    stockEpcBean.MURoNo = bean.MURoNo
                    stockEpcBean.SRoNo = bean.SRoNo
                    stockEpcBean.type = 1
                    epcBean.Type = 1
                    stockEpcBean.BatchNo = mViewModel.batchNo.get()
                    stockEpcBean.createTime = TimeUtils.getNowString()
                    mViewModel.stockManageEpcDao.insertOrUpdate(stockEpcBean)
                    eventViewModel.playMusic.postValue(true)

                    dataBean?.Info?.let { infoList ->
                        val skuAllResults = infoList.map { info ->
                            mViewModel.stockManageEpcDao.findSkuAll(stockEpcBean.ids!!, info.MURoNo!!, mViewModel.batchNo.get())
                        }
                        infoList.zip(skuAllResults).forEach { (info, skuAll) ->
                            info.allNum = skuAll.size
                        }
                    }
                    val count = dataBean?.Info?.sumOf { it.NeedNum } ?: 0

                    val skuAll = mViewModel.stockManageEpcDao.findSkuAll(stockEpcBean.ids!!, mViewModel.batchNo.get())
                    if (skuAll.size == count) {
                        dataBean?.Type = 1
                    }
                    dataBean.BatchNo = mViewModel.batchNo.get()
                    Handler(Looper.getMainLooper()).post {
                        adapter.setData(index, dataBean)
                    }
                }
            }
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        //设置界面 加载中
        loadsir.showLoading()
        mViewModel.onStockManageList(mViewModel.batchNo.get(), stockType, mViewModel.code.get())
    }

    inner class ProxyClick() {
        fun save(){
            mViewModel.onSubmit(this@StockManageListFrg,
                adapter.data as ArrayList<DataBean>, mViewModel.batchNo.get(), stockType, mViewModel.code.get())
        }

        fun state(){
            if (adapter.data.size == 0)return
            mViewModel.viewModelScope.launch(Dispatchers.IO) {
                val configBean = mViewModel.configDao.findFirst()
                configBean.powerType = 0
                mViewModel.configDao.update(configBean)
                if (mViewModel.state.get().equals(getString(R.string.start))){
                    mViewModel.state.set(getString(R.string.stop))
                    rfidModel.isOpen.postValue(true)
                }else{
                    mViewModel.state.set(getString(R.string.start))
                    rfidModel.isOpen.postValue(false)
                }
            }
        }
    }

}